<template>
  <div class="anniversary-view">
    <AppHeader title="倒数纪念日">
      <template #left>
        <el-button circle @click="router.back()">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
      </template>
    </AppHeader>

    <div v-if="nearestAnniversary" class="featured-anniversary">
      <h2>{{ nearestAnniversary.title }}</h2>
      <div class="countdown">{{ countdownDisplay }}</div>
      <div class="target-date">目标日期: {{ nearestAnniversary.targetDate }}</div>
    </div>
    <div v-else class="featured-anniversary">
      <h2>没有即将到来的纪念日</h2>
    </div>

    <div class="all-anniversaries-list">
      <h2>所有纪念日</h2>
      <ul>
        <li v-for="anniversary in sortedAnniversaries" :key="anniversary.id" class="anniversary-list-item">

          <!-- Edit Actions (Hidden on left) -->
          <div class="item-actions edit-actions">
            <el-button type="primary" size="small" @click.stop="handleEditAnniversary(anniversary.id)">编辑</el-button>
          </div>

          <!-- Main Content Wrapper (Slidable) -->
          <div 
            class="item-main-wrapper"
            :style="{ transform: itemTransform(anniversary.id) }"
            @click.stop="handleItemClick(anniversary, $event)"
          >
            <div class="item-left">
              <div class="anniversary-item-title">{{ anniversary.title }}</div>
              <div class="anniversary-item-date">{{ dayjs(anniversary.targetDate).format('YYYY.MM.DD') }}</div>
            </div>
            <div class="item-right">
               {{ anniversary.remainingDays.replace('剩余 ', '').replace(' 天', '') }}
              <span class="days-label">天后</span>
            </div>
          </div>

          <!-- Delete Actions (Hidden on right) -->
          <div class="item-actions delete-actions">
            <el-button type="danger" size="small" @click.stop="confirmDelete(anniversary.id)">删除</el-button>
          </div>

        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs' // 使用 dayjs 库处理日期和时间
import duration from 'dayjs/plugin/duration' // 引入 duration 插件
import relativeTime from 'dayjs/plugin/relativeTime' // 引入 relativeTime 插件
import AppHeader from '../components/AppHeader.vue'
import { useRouter } from 'vue-router' // Import useRouter for navigation
import { ElMessageBox } from 'element-plus' // Import ElMessageBox
import { ArrowLeft } from '@element-plus/icons-vue'

dayjs.extend(duration)
dayjs.extend(relativeTime)

export default {
  name: 'AnniversaryView',
  components: {
    AppHeader,
    ArrowLeft,
  },
  setup() {
    const anniversaries = ref([])
    const nearestAnniversary = ref(null)
    const countdownDisplay = ref('加载中...')
    let countdownTimer = null
    const router = useRouter() // Initialize useRouter

    // State to track which item's actions are open: { id: number, action: 'edit' | 'delete' | null }
    const openItemId = ref(null);
    const openItemAction = ref(null);

    const fetchAnniversaries = async () => {
      try {
        const response = await axios.get('http://localhost:8080/anniversary/list')
        if (response.data && Array.isArray(response.data)) {
          anniversaries.value = response.data
          findNearestAnniversary()
        }
      } catch (error) {
        console.error('Error fetching anniversaries:', error)
      }
    }

    const findNearestAnniversary = () => {
      const now = dayjs()
      // Filter for future anniversaries and sort them by targetDate
      const futureAnniversaries = anniversaries.value
        .filter(ann => dayjs(ann.targetDate).isAfter(now))
        .sort((a, b) => dayjs(a.targetDate).diff(now) - dayjs(b.targetDate).diff(now))

      if (futureAnniversaries.length > 0) {
        nearestAnniversary.value = futureAnniversaries[0]
        startCountdown()
      } else if (anniversaries.value.length > 0) {
        // If no future anniversaries, maybe show the one closest in the past?
        // For now, we will just indicate no upcoming ones.
        nearestAnniversary.value = null;
        countdownDisplay.value = '没有即将到来的纪念日';
        stopCountdown();
      }
    }

    const calculateCountdown = (targetDate) => {
      const now = dayjs()
      const target = dayjs(targetDate)
      if (target.isBefore(now)) {
        return '已过期'
      }

      const diff = target.diff(now)
      const duration = dayjs.duration(diff)

      const days = Math.floor(duration.asDays())
      const hours = duration.hours()
      const minutes = duration.minutes()
      const seconds = duration.seconds()

      return `${days}天${hours}时${minutes}分${seconds}秒`
    }

    const startCountdown = () => {
      stopCountdown(); // Clear any existing timer
      if (nearestAnniversary.value) {
        countdownTimer = setInterval(() => {
          countdownDisplay.value = calculateCountdown(nearestAnniversary.value.targetDate)
        }, 1000)
      }
    }

    const stopCountdown = () => {
      if (countdownTimer) {
        clearInterval(countdownTimer)
        countdownTimer = null
      }
    }

    // Sort all anniversaries for the list display (e.g., by target date)
    const sortedAnniversaries = computed(() => {
      return [...anniversaries.value].sort((a, b) => dayjs(a.targetDate).diff(dayjs(b.targetDate)))
    })

    const goToAnniversaryDetail = (id) => {
      router.push({ name: 'AnniversaryDetail', params: { id: id } })
    }

    const handleDeleteAnniversary = async (id) => {
      try {
        // Assuming the delete API is DELETE /anniversary/delete?id=id
        const response = await axios.delete(`http://localhost:8080/anniversary/delete`, {
          params: { id: id }
        })
        // Assuming a successful delete returns code 0 or similar, or just a 200 status
        if (response.status === 200) { // Check for HTTP 200 status
          // Remove the deleted anniversary from the list
          anniversaries.value = anniversaries.value.filter(ann => ann.id !== id)
          // Re-evaluate the nearest anniversary if needed
           findNearestAnniversary();
          console.log(`纪念日 ${id} 删除成功`)
          // Optionally show a success message
        } else {
           console.error(`删除纪念日 ${id} 失败:`, response.data);
           // Optionally show a failure message
        }
      } catch (error) {
        console.error(`删除纪念日 ${id} 出错:`, error)
        // Optionally show an error message
      }
    }

    const confirmDelete = (id) => {
       ElMessageBox.confirm(
          '确定要删除这个纪念日吗？',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        .then(() => {
          handleDeleteAnniversary(id);
        })
        .catch(() => {
          // Catch is called when user clicks cancel or closes the dialog
           console.log('删除操作已取消');
           closeOpenItem(id); // Close action panel on cancel
        });
    }

    const handleEditAnniversary = (id) => {
      // Navigate to the edit page
      router.push({ name: 'AnniversaryEdit', params: { id: id } })
      closeOpenItem(id); // Close action panel after navigating
    }

    // Handle click on the main item content area
    const handleItemClick = (anniversary, event) => {
      const itemWidth = event.currentTarget.offsetWidth;
      const clickX = event.clientX - event.currentTarget.getBoundingClientRect().left;

      const editThreshold = itemWidth * (1/5); // Left 1/5
      const deleteThreshold = itemWidth * (4/5); // Right 1/5

      if (openItemId.value === anniversary.id) {
          // If this item's actions are already open, clicking main content closes them
          closeOpenItem(anniversary.id);
      } else if (clickX < editThreshold) {
          // Clicked in the left 1/5 area - show edit actions
          openItem(anniversary.id, 'edit');
      } else if (clickX > deleteThreshold) {
          // Clicked in the right 1/5 area - show delete actions
          openItem(anniversary.id, 'delete');
      } else {
          // Clicked in the middle area - go to detail page
          goToAnniversaryDetail(anniversary.id);
      }
       // Stop propagation to prevent the click on li from closing other items
       event.stopPropagation();
    };

    // Open actions for a specific item
    const openItem = (id, action) => {
       // Close any currently open item if it's different
       if (openItemId.value !== null && openItemId.value !== id) {
           closeOpenItem(openItemId.value);
       }
       openItemId.value = id;
       openItemAction.value = action;
    };

    // Close actions for a specific item
    const closeOpenItem = (id) => {
        if (openItemId.value === id) {
            openItemId.value = null;
            openItemAction.value = null;
        }
    };

    // Calculate transform for the main wrapper
    const itemTransform = computed(() => (id) => {
        if (openItemId.value === id) {
            if (openItemAction.value === 'edit') {
                // Slide right to reveal edit button (assume edit button width is ~1/5 of item)
                // We need to know the actual width of the actions area.
                // For now, use a placeholder value like 80px or calculate based on flex-basis
                const actionWidth = 80; // Placeholder width, adjust based on CSS
                return `translateX(${actionWidth}px)`;
            } else if (openItemAction.value === 'delete') {
                 const actionWidth = 80; // Placeholder width, adjust based on CSS
                // Slide left to reveal delete button
                return `translateX(-${actionWidth}px)`;
            }
        }
        return 'translateX(0)'; // Normal state
    });

    // Close open item when clicking anywhere outside the list
    onMounted(() => {
       fetchAnniversaries();
       document.addEventListener('click', handleDocumentClick);
    });

    onUnmounted(() => {
       stopCountdown();
       document.removeEventListener('click', handleDocumentClick);
    });

    const handleDocumentClick = () => {
        // Close any open item when clicking outside
        // Check if clicking inside an anniversary item before closing
        // This requires checking the event target and its ancestors
        // For simplicity, we'll close if not clicking inside the list for now.
        // A more robust solution would check if the click target is *within* any .anniversary-list-item
        // If openItemId.value is not null, and the click is not within that item,
        // then close that item.
         // Re-checking if the click target is *not* within any .anniversary-list-item
        if (openItemId.value !== null) {
            let targetElement = event.target;
            let isInsideItem = false;
            while(targetElement) {
                if (targetElement.classList && targetElement.classList.contains('anniversary-list-item')) {
                    isInsideItem = true;
                    break;
                }
                targetElement = targetElement.parentElement;
            }
            if (!isInsideItem) {
                 closeOpenItem(openItemId.value);
            }
        }
    };

    return {
      anniversaries,
      nearestAnniversary,
      countdownDisplay,
      sortedAnniversaries,
      dayjs,
      goToAnniversaryDetail,
      handleDeleteAnniversary,
      handleEditAnniversary,
      confirmDelete,
      itemTransform, // Expose computed property to template
      handleItemClick, // Expose click handler
      closeOpenItem, // Expose close function for use in template if needed, though handled by document click
      router,
      ArrowLeft
    }
  }
}
</script>

<style scoped>
.anniversary-view {
  padding: 15px;
  /* Add some padding at the top to account for the fixed header */
  padding-top: 60px; /* Adjust based on actual header height */
}

.anniversary-header {
  /* Style for the header if needed, or remove if using a global header */
}

.featured-anniversary {
  background-color: #e3f2fd; /* Light blue background */
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.featured-anniversary h2 {
  color: #1e88e5; /* Darker blue for title */
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 20px;
}

.countdown {
  font-size: 24px;
  font-weight: bold;
  color: #0d47a1; /* Even darker blue for countdown */
  margin-bottom: 10px;
}

.target-date {
  font-size: 14px;
  color: #555;
}

.all-anniversaries-list h2 {
  font-size: 18px;
  margin-bottom: 15px;
  color: #333;
}

.all-anniversaries-list ul {
  list-style: none;
  padding: 0;
}

.anniversary-list-item {
  background-color: #fff;
  border-radius: 10px;
  padding: 0; /* Remove padding from the list item itself */
  margin-bottom: 10px;
  display: flex; /* Use flexbox for layout */
  align-items: stretch; /* Make items fill the height */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.08);
  border-left: 5px solid #42a5f5;
  cursor: pointer; /* Indicate clickable */
  position: relative;
  overflow: hidden;
  /* Removed min-height to let content dictate height */
}

.item-main-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-grow: 1; /* Allows wrapper to take up available space */
    background-color: #fff; /* Background for the sliding wrapper */
    transition: transform 0.3s ease; /* Smooth sliding animation */
    /* Internal padding for the content within the sliding wrapper */
    padding: 15px 20px;
    width: 100%; /* Ensure the wrapper takes full width initially */
    box-sizing: border-box; /* Include padding in the element's total width */
     /* Add z-index to ensure it's above action buttons */
    z-index: 1;
}

/* Styles for the fixed action buttons */
.item-actions {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center; /* Center buttons within action area */
    width: 80px; /* Fixed width for action area, adjust as needed */
     /* Removed padding from here */
     /* Add z-index lower than main wrapper */
     z-index: 0;
}

.edit-actions {
    left: 0; /* Position edit actions on the left */
    background-color: #66b1ff; /* Edit background color */
    color: white;
     /* Adjust position based on transform amount in JS if needed */
}

.delete-actions {
    right: 0; /* Position delete actions on the right */
    background-color: #f56c6c; /* Delete background color */
    color: white;
     /* Adjust position based on transform amount in JS if needed */
}

.item-actions .el-button {
  height: 100%; /* Make buttons fill the height */
  border-radius: 0; /* Square corners for buttons */
  padding: 0 10px; /* Padding inside button */
  border: none; /* Remove button border */
  background: none; /* Remove button background */
  color: inherit; /* Inherit text color from parent action area */
}

.item-actions .el-button .el-icon {
    margin-right: 0; /* No margin for icon in action button */
}

/* Styles for the content within the sliding wrapper */
/* Removed .item-main-content as content is directly within .item-main-wrapper */

.item-left {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  align-items: flex-start;
}

.item-right {
  display: flex;
  align-items: baseline;
  font-size: 20px;
  font-weight: bold;
  color: #1e88e5;
  flex-shrink: 0;
}

.anniversary-item-title {
  margin-bottom: 5px;
}

.anniversary-item-date {
  font-size: 12px;
  color: #999;
}

.days-label {
  font-size: 12px;
  font-weight: normal;
  color: #fff;
  background-color: #42a5f5;
  border-radius: 4px;
  padding: 2px 6px;
  margin-left: 4px;
}

/* Optional: Styles for icons within the detail area if needed */
/* Removed .item-detail-area and its icon styles */

</style> 